<template>
  <div class="login-bg">
    <el-card class="login-card">
      <h2 class="login-title">登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="70px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="loginForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-row :gutter="10" align="middle">
            <el-col :span="14">
              <el-input v-model="loginForm.captcha" maxlength="5" autocomplete="off" />
            </el-col>
            <el-col :span="10">
              <div class="captcha-box" @click="generateCaptcha">{{ captcha }}</div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin" :loading="loading" style="width:100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { Phone } from '@element-plus/icons-vue'

const router = useRouter()
const loginForm = ref({
  phone: '12312341234',
  password: 'admin123',
  captcha: '',
  remember: false
})
const loading = ref(false)
const loginFormRef = ref()
const captcha = ref('')

function randomCaptcha(len = 5) {
  const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
  let str = ''
  for (let i = 0; i < len; i++) {
    str += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return str
}

function generateCaptcha() {
  captcha.value = randomCaptcha()
}

onMounted(() => {
  generateCaptcha()
  // 自动填充记住的账号
  const saved = localStorage.getItem('rememberedUser')
  if (saved) {
    try {
      const user = JSON.parse(saved)
      loginForm.value.phone = user.phone || ''
      loginForm.value.password = user.password || ''
      loginForm.value.remember = true
    } catch { }
  }
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback(new Error('请输入验证码'))
        } else if (value.toLowerCase() !== captcha.value.toLowerCase()) {
          callback(new Error('验证码错误'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
}

const onLogin = () => {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      // 调用后端登录接口
      const res = await fetch(`http://59.110.150.130:8089/api/app/user/login?Phone=${encodeURIComponent(loginForm.value.phone)}&Password=${encodeURIComponent(loginForm.value.password)}`, {
        method: 'POST',
        headers: { 'accept': 'text/plain' }
      })
      const data = await res.json()
      if (data.code === 200) {
        ElMessage.success('登录成功')
        
        // 记住密码
        if (loginForm.value.remember) {
          localStorage.setItem('rememberedUser', JSON.stringify({
            phone: loginForm.value.phone,
            password: loginForm.value.password
          }))
        } else {
          localStorage.removeItem('rememberedUser')
        }
        // 存储用户信息和 token
        localStorage.setItem('userName', data.resultData.userName)
        localStorage.setItem('token', 'valid_token') // 确保存储 token

        const today = new Date().toDateString();
        const lastLoginDate = localStorage.getItem("lastLoginDate");

        var loginNum = +(localStorage.getItem("loginNum") || 0);
        var logShowFlag = +(localStorage.getItem("logShowFlag") || 0);

        // 新的一天，重置数据
        if (lastLoginDate !== today) {
          loginNum = 0;
          logShowFlag = 0;
          localStorage.setItem("lastLoginDate", today);
        }

        // 判断登录次数逻辑
        if (loginNum === 0) {
          // 当天首次登录
          loginNum = 1;
          logShowFlag = 1; // 设置显示日志标识
        } else if (loginNum >= 1) {
          // 非首次登录
          loginNum += 1;
          // 只有在 logShowFlag 不是 2 的情况下才设置为 2
          if (logShowFlag !== 2) {
            logShowFlag = 2;
          }
        }

        // 保存数据
        localStorage.setItem("loginNum", loginNum.toString());
        localStorage.setItem("logShowFlag", logShowFlag.toString());

        // 确保跳转到 Main 页面
        router.push('/Main').catch(() => {})
      } else {
        ElMessage.error(data.message || '登录失败')
        generateCaptcha()
      }
    } catch (e) {
      ElMessage.error('网络错误')
      generateCaptcha()
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('../assets/hzp_bg.png') no-repeat center center;
  background-size: cover;
}

.login-card {
  width: 350px;
  padding: 30px 20px 20px 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.95);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-weight: bold;
  font-size: 22px;
  color: #333;
}

.captcha-box {
  user-select: none;
  background: #f5f5f5;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 10px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  font-size: 18px;
  letter-spacing: 2px;
  cursor: pointer;
  color: #409eff;
  font-weight: bold;
}
</style>
